package com.bw.dim;

import com.alibaba.fastjson.JSONObject;
import com.bw.bean.TableProcess;
import com.bw.func.TableProcessFunction;
import com.bw.utils.MyKafkaUtil;
import com.bw.utils.MyPhoenixSink;
import com.bw.utils.MysqlUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author y3068
 * @Classname Test1
 * @Description TODO
 * @Date 2025/6/19 15:09
 * @Version V1.0
 */

public class Test1 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // TODO 设置并行度
        env.setParallelism(1);
//        env.enableCheckpointing(5*60000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(10*60000L);
//        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
//        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,5000L));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/flink_gmall/ck");
//        System.setProperty("HADOOP_USER_NAME","ROOT");

        String topic = "topic_db";
        String groupId = "dimapp";

        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        ds.print("我是同步业务数据 通过Maxwell 增量同步到topic_db");


        SingleOutputStreamOperator<JSONObject> ds1 = ds.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                JSONObject object = JSONObject.parseObject(s);
                String type = object.getString("type");
                if (type.equals("insert") || type.equals("update") || type.equals("bootstrap_insert")) {
                    collector.collect(object);
                } else {
                    System.out.println("不是json数据" + s);
                }
            }
        });

        ds1.print("过滤之后的数据");

        DataStream<String> MysqlDs = MysqlUtil.cdcMysql(env, "gmall_config", "table_process");
        MysqlDs.print("mysql数据");

        MapStateDescriptor<String, TableProcess> mapState = new MapStateDescriptor<>("mapState", String.class, TableProcess.class);

        BroadcastStream<String> broadcastDs = MysqlDs.broadcast(mapState);

        BroadcastConnectedStream<JSONObject, String> connect = ds1.connect(broadcastDs);

        SingleOutputStreamOperator<JSONObject> dimDS = connect.process(new TableProcessFunction(mapState));
        dimDS.print("dimDS");

        dimDS.addSink(new MyPhoenixSink());

        env.execute();

    }
}
